# 
# nested_class_methods.rb
# 
# Created on 09/08/2007, 16:39:13
# 
# This set of methods is meant to work WITH a parent resource.
# See main module RestClassMethods
 
module AutoRest
module RestInstanceMethods
  
  module ModelManipulation
  private

    def ar_get_records_source
      # AutoRest ARDataContainer holds a helper to determine wich model
      # to use given the current params.
      @parent_resource= ardata.parent_resource_model(request.parameters)
      ar_set_parent_instance_var
      
      if block_given?
        # When dealing with non-nested resources, or parent_id not present,
        # the parent will be nil. 
        if @parent_resource
          records_source= @parent_resource.send(ardata.resource.plural)
        else
          records_source= ardata.resource.model       
        end

        yield records_source

        instance_variable_set("@#{ardata.resource.plural}", @resources)
        instance_variable_set("@#{ardata.resource.singular}", @resource)
      end
      
      @parent_resource
    end
    
    def ar_set_parent_instance_var
      return unless @parent_resource
      parent_resource_name= @parent_resource.class.class_name.underscore
      instance_variable_set("@#{parent_resource_name}", @parent_resource)
    end

    def ar_get_resources options= {}
      ar_get_records_source do |parent|
        options.reverse_merge! ardata.index_finder if ardata.index_finder

        if ardata.will_paginate.enabled
          options[:page]||= (params[:page] || 1)
          @resources= parent.paginate(options)
        else
          @resources= parent.find(:all, options)
        end
      end
    end

    def ar_get_resource id= params[:id]
      ar_get_records_source do |parent|
        @resource= parent.find_by_id(id)
      end
    end

    def ar_new_resource params= nil
      ar_get_records_source do |parent|
        @resource= parent.new(params)
      end
    end

    def ar_create_resource params= params[:resource]
      ar_get_records_source do |parent|
        # Collections comming from reflections needs build, AR needs new.
        if parent.respond_to? :build
          @resource= parent.build(params)
        else
          @resource= parent.new(params)
        end
      end
    end

    # ----------------------------------------------------------------------------

    # Common methods for updating, saving and destroying resource.
    # May be redefined to change behavior.
    def ar_save_resource
      @resource.save
    end

    def ar_update_resource_attributes options= params[:resource]
      @resource.update_attributes(options)
    end

    def ar_destroy_resource
      @resource.destroy
    end
    
  end #module ModelManipulation

end #module RestInstanceMethods
end #module AutoRest  